import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/entity/home/news_comment_entity.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/utils/app_config.dart';

class NewsDetailLogic extends BaseController {
  int newsId = "${Get.arguments}".toInt() ?? 0;
  int? classId = int.tryParse(Get.parameters['classId'] ?? "");
  String id = Get.parameters['id'] ?? "";
  final scrollC = ApmScrollController();
  late final observer = SliverObserverController(controller: scrollC);
  bool showTop = false;
  NewsItemEntity? data;
  List<PlanEntity>? plan;
  List<NewsCommentEntity>? comments;
  int commentIndex = 1;
  int _commentSort = 1;

  int get commentSort => _commentSort;

  set commentSort(int value) {
    _commentSort = value;
    update();
  }

  bool get showRelative =>
      data?.list?.hasValue == true && AppConfig.config.showRelative;

  @override
  void onInit() {
    scrollC.addListener(() {
      if (scrollC.offset > 60 && showTop == false) {
        showTop = true;
        update();
      } else if (scrollC.offset < 60 && showTop == true) {
        showTop = false;
        update();
      }
    });
    super.onInit();
  }

  @override
  void onReady() {
    getNews();
    getComments();
    super.onReady();
  }

  getNews() {
    HomeApi.getNews2(newsId, classId: classId).then((value) {
      data = value;
      data?.classId = classId;
      // fetchRecommend();
      // commentsController.updateNews(data);
      getPlan();
      update();
    }).catchError((err) {});
  }

  onZan() async {
    if (data == null) {
      return;
    }
    if (data?.type == 2) {
      if (data?.isLike == 1) {
        final result = await HomeApi.newsSupport(data!.id!, type: 4);
        if (result == 200) {
          data!.isLike = 0;
          data!.likeNum = data!.likeNum! - 1;
          Toast.text("已取消点赞");
        }
      } else {
        final result = await HomeApi.newsSupport(data!.id!, type: 2);
        if (result == 200) {
          data!.isLike = 1;
          data!.likeNum = data!.likeNum! + 1;
          Toast.text("点赞成功");
        }
      }
    } else {
      if (data?.isLike == 1) {
        final result = await HomeApi.newsSupport(data?.id ?? 0, type: 4);
        if (result == 200) {
          data?.isLike = 0;
          data!.likeNum = data!.likeNum! - 1;
          Toast.text("已取消点赞");
        }
      } else {
        final result = await HomeApi.newsSupport(data?.id ?? 0, type: 2);
        if (result == 200) {
          data?.isLike = 1;
          data!.likeNum = data!.likeNum! + 1;
          Toast.text("点赞成功");
        }
      }
    }
    Utils.onEvent("article_like",
        params: {"article_id": data?.id, "like": data?.isLike, "channel": id});
    update();
  }

  onCollect() async {
    if (data?.collectId == 1) {
      final result = await UserApi.deleteCollect(data!.id!);
      if (result == 200) {
        data?.collectId = 0;
        Toast.text('取消收藏成功');
      }
    } else {
      final result = await UserApi.collect(data?.type ?? 1, data?.id ?? 0);
      if (result == 200) {
        data?.collectId = 1;
        Toast.text("收藏成功");
      }
    }
    Utils.onEvent("article_collect", params: {
      "article_id": data?.id,
      "collect": data?.collectId,
      "channel": id
    });
    update();
  }

  Future getPlan() async {
    if (data?.topMatchId?.hasValue == true) {
      plan = await ExpertApi.getNewsPlan(data?.topMatchId, 1);
    }
  }

  Future getComments() async {
    commentIndex = 1;
    comments = await HomeApi.getCommentList(newsId,
        page: commentIndex, type: commentSort);
    update();
  }

  Future loadComments() async {
    commentIndex += 1;
    final r = await HomeApi.getCommentList(newsId,
        page: commentIndex, type: commentSort);
    if (r.hasValue) {
      comments?.addAll(r);
    }
    refreshController.finishLoad((comments?.length ?? 0) < commentIndex * 20
        ? IndicatorResult.noMore
        : IndicatorResult.success);
    update();
  }

  Future sendChat(
      TextEditingController textController, FocusNode inputFocus) async {
    if (textController.text.noValue) {
      Toast.text("发言内容不能为空");
      return;
    }
    Utils.onEvent("article_comment",
        params: {"article_id": data?.id, "channel": id});
    final r = await HomeApi.add(newsId, textController.text);
    if (r.data['c'] == 200) {
      NewsCommentEntity.fromJson(r.data['d']);
    }
    textController.clear();
    inputFocus.unfocus();
    update();
  }

  @override
  void getRefresh() {
    try {
      getNews();
      getComments();
    } catch (e) {
      Logger().d(e);
    }
    super.getRefresh();
  }

  @override
  void loadMore() {
    loadComments();
    super.loadMore();
  }

  Future report(NewsCommentEntity comment, String reason) async {
    await HomeApi.support(comment.id ?? 0, type: 2, newsId: newsId);
  }

  Future changeLike(int like, int index) async {
    var r = await HomeApi.support(comments![index].id ?? 0,
        type: like == 1 ? 1 : 3, newsId: newsId);
    if (r == 200) {
      comments![index].isLike = like;
      if (comments![index].likeNum.hasValue) {
        comments![index].likeNum =
            comments![index].likeNum! + (like == 1 ? 1 : -1);
      } else {
        if (like == 1) comments![index].likeNum = 1;
      }
    }
    update();
  }

  Future delete(NewsCommentEntity comment, int index) async {
    var r = await HomeApi.deleteComment(comment.id ?? 0);
    if (r == 200) {
      comments?.removeAt(index);
    }
    update();
  }

  void toComment() {
    var index = 3;
    if (!showRelative) index -= 1;
    if (plan.noValue) index -= 1;
    observer.animateTo(
        index: index,
        duration: const Duration(milliseconds: 200),
        curve: Curves.ease);
  }
}
